package utils

import (
	"fmt"
	"os"
	"runtime"
	"strings"
	"time"

	"github.com/iwen-conf/colorprint/clr"
)

// GetProjectName 从go.mod文件中获取项目名称
func GetProjectName() (string, error) {
	// 读取go.mod文件
	modData, err := os.ReadFile("go.mod")
	if err != nil {
		return "", fmt.Errorf("无法读取go.mod文件: %v", err)
	}

	lines := strings.Split(string(modData), "\n")
	for _, line := range lines {
		if strings.HasPrefix(line, "module ") {
			modulePath := strings.TrimSpace(strings.TrimPrefix(line, "module "))
			// 提取最后一个部分作为项目名称
			parts := strings.Split(modulePath, "/")
			return parts[len(parts)-1], nil
		}
	}

	return "", fmt.Errorf("在go.mod中找不到module定义")
}

// RunAsProgramInfo 显示系统信息
func RunAsProgramInfo() {
	header := clr.BGColor(clr.FGColor("欢迎使用交叉编译测试程序", clr.White), clr.BgBlue)
	fmt.Println(clr.Bold("=================================="))
	fmt.Println(clr.Bold(header))
	fmt.Println(clr.Bold("=================================="))

	fmt.Printf("%s: %s\n", clr.Bold("当前操作系统"), clr.FGColor(runtime.GOOS, clr.Green))
	fmt.Printf("%s: %s\n", clr.Bold("当前系统架构"), clr.FGColor(runtime.GOARCH, clr.Green))
	fmt.Printf("%s: %s\n", clr.Bold("Go版本"), clr.FGColor(runtime.Version(), clr.Green))

	fmt.Println(clr.Bold("=================================="))

	hostname, _ := os.Hostname()
	fmt.Printf("%s: %s\n", clr.Bold("主机名"), clr.FGColor(hostname, clr.Cyan))

	dir, err := os.Getwd()
	workDir := "未知"
	if err == nil {
		workDir = dir
	}
	fmt.Printf("%s: %s\n", clr.Bold("当前工作目录"), clr.FGColor(workDir, clr.Cyan))

	fmt.Println(clr.Bold("=================================="))
}

// PrintHelp 打印帮助信息
func PrintHelp() {
	title := clr.FGColor("BuildAll - Go 交叉编译工具", clr.Green)
	fmt.Println(clr.Bold(title))
	fmt.Println()

	fmt.Println(clr.Bold("使用说明:"))
	fmt.Printf("  %s\t%s\n", clr.FGColor("go run main.go", clr.Cyan), "运行程序并显示系统信息")
	fmt.Printf("  %s\t%s\n", clr.FGColor("go run main.go --build", clr.Cyan), "构建所有支持的平台")
	fmt.Printf("  %s\t%s\n", clr.FGColor("go run main.go --build-os=xxx", clr.Cyan), "只构建指定的操作系统(多个用逗号分隔)")
	fmt.Printf("  %s\t%s\n", clr.FGColor("go run main.go --build-arch=xxx", clr.Cyan), "只构建指定的架构(多个用逗号分隔)")
	fmt.Printf("  %s\t%s\n", clr.FGColor("go run main.go --detail", clr.Cyan), "显示详细的构建报告")
	fmt.Printf("  %s\t%s\n", clr.FGColor("go run main.go --help", clr.Cyan), "显示此帮助信息")

	fmt.Println()
	fmt.Println(clr.Bold("示例:"))
	example1 := clr.FGColor("go run main.go --build-os=linux,windows --build-arch=amd64,arm64", clr.Cyan)
	fmt.Printf("  %s\n", example1)
	fmt.Printf("  %s\n", "这将只构建 linux/amd64, linux/arm64, windows/amd64, windows/arm64")

	example2 := clr.FGColor("go run main.go --build --detail", clr.Cyan)
	fmt.Printf("\n  %s\n", example2)
	fmt.Printf("  %s\n", "构建所有平台并显示详细报告")
}

// ParseArgs 解析命令行参数
func ParseArgs() (bool, []string, []string, bool, bool) {
	var buildMode bool
	var targetOS, targetArch []string
	var helpMode, detailMode bool

	for _, arg := range os.Args[1:] {
		if arg == "--build" {
			buildMode = true
		} else if arg == "--help" || arg == "-h" {
			helpMode = true
		} else if arg == "--detail" || arg == "-d" {
			detailMode = true
		} else if strings.HasPrefix(arg, "--build-os=") {
			osList := strings.TrimPrefix(arg, "--build-os=")
			if osList != "" {
				targetOS = strings.Split(osList, ",")
			}
			buildMode = true
		} else if strings.HasPrefix(arg, "--build-arch=") {
			archList := strings.TrimPrefix(arg, "--build-arch=")
			if archList != "" {
				targetArch = strings.Split(archList, ",")
			}
			buildMode = true
		}
	}

	// 验证目标OS和架构，并输出彩色警告
	if len(targetOS) > 0 {
		for _, os := range targetOS {
			if !IsValidOS(os) {
				fmt.Println(clr.FGColor(fmt.Sprintf("警告: 不支持的操作系统 '%s'", os), clr.Yellow))
			}
		}
	}

	if len(targetArch) > 0 {
		for _, arch := range targetArch {
			if !IsValidArch(arch) {
				fmt.Println(clr.FGColor(fmt.Sprintf("警告: 不支持的架构 '%s'", arch), clr.Yellow))
			}
		}
	}

	return buildMode, targetOS, targetArch, helpMode, detailMode
}

// IsValidOS 检查操作系统是否受支持
func IsValidOS(os string) bool {
	supportedOS := []string{"linux", "darwin", "windows", "freebsd", "openbsd", "netbsd", "dragonfly", "solaris", "plan9", "aix", "android", "ios"}
	for _, supported := range supportedOS {
		if os == supported {
			return true
		}
	}
	return false
}

// IsValidArch 检查架构是否受支持
func IsValidArch(arch string) bool {
	supportedArch := []string{"386", "amd64", "arm", "arm64", "ppc64", "ppc64le", "mips", "mipsle", "mips64", "mips64le", "riscv64", "s390x", "wasm"}
	for _, supported := range supportedArch {
		if arch == supported {
			return true
		}
	}
	return false
}

// ShowProgress 显示进度条
func ShowProgress(current, total int, width int) {
	percent := float64(current) / float64(total)
	filled := int(percent * float64(width))

	// 清除当前行
	fmt.Printf("\r")

	bar := ""
	for i := 0; i < width; i++ {
		if i < filled {
			bar += "="
		} else if i == filled {
			bar += ">"
		} else {
			bar += " "
		}
	}

	progressBar := fmt.Sprintf("[%s]", bar)
	percentage := fmt.Sprintf("%.1f%%", percent*100)
	count := fmt.Sprintf("(%d/%d)", current, total)

	// 打印彩色进度条
	fmt.Printf("%s %s %s",
		clr.FGColor(progressBar, clr.Cyan),
		clr.FGColor(percentage, clr.Green),
		clr.FGColor(count, clr.Magenta))
}

// GetElapsedTime 计算时间间隔并格式化为友好显示
func GetElapsedTime(startTime time.Time) string {
	elapsed := time.Since(startTime)

	// 格式化为更友好的显示
	if elapsed < time.Second {
		return fmt.Sprintf("%dms", elapsed.Milliseconds())
	} else if elapsed < time.Minute {
		return fmt.Sprintf("%.1fs", elapsed.Seconds())
	} else {
		mins := int(elapsed.Minutes())
		secs := int(elapsed.Seconds()) % 60
		return fmt.Sprintf("%dm%ds", mins, secs)
	}
}

// Contains 判断字符串是否在切片中
func Contains(slice []string, item string) bool {
	for _, s := range slice {
		if s == item {
			return true
		}
	}
	return false
}
